package com.erp.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.DateUtil;
import com.erp.entity.Demand;
import com.erp.entity.Label;
import com.erp.entity.Project;
import com.erp.enums.moduleName;
import com.erp.enums.statusCode;
import com.erp.mapper.ProjectMapper;
import com.erp.service.DemandService;
import com.erp.service.LabelService;
import com.erp.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 项目展示 前端控制器
 * </p>
 *
 * @author CJ
 * @since 2021-08-23
 */
@Slf4j
@Controller
@RequestMapping("/projectView")
public class projectViewController {
    @Resource
    ProjectService projectService;
    @Resource
    LabelService labelService;
    @Resource
    DemandService demandService;
    @Resource
    ProjectMapper projectMapper;
    @GetMapping("/one")
//    @PreAuthorize("hasAnyAuthority('projectView:list')")
    public ModelAndView indexOne() {
        log.error(moduleName.projectView.getMsg());
        ModelAndView modelAndView = new ModelAndView();
        List<Project> projectList = projectService.list(new QueryWrapper<Project>()
                .eq("status",statusCode.Default.getValue()).select("distinct project_name"));
        List<Label> labelList = labelService.list(new QueryWrapper<Label>().eq("status",statusCode.Default.getValue())
                .select("label_name"));
        modelAndView.addObject("labelList", labelList);
        modelAndView.addObject("listProject", projectList);
        modelAndView.setViewName("system/index/indexOne");
        return modelAndView;
    }

    // 列表数据1
    @RequestMapping(value = "/getOneList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOneList(
            @RequestParam(value = "page") int page,
            @RequestParam(value = "limit") int limit,
            @RequestParam(value = "startTime",required=false) String startTime,
            @RequestParam(value = "endTime",required=false) String endTime,
            @RequestParam(value = "labelName",required=false) String labelName,
            @RequestParam(value = "projectName",required=false) String projectName) {
        IPage<Demand> demandPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<Demand> wrapper = new QueryWrapper<>();
        //判断一下是否有搜索条件
        if (StrUtil.isNotEmpty(labelName)){
            wrapper.like("label_name",labelName);
        }
        if (StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime)){
            // 时间偏于一天
            Date date = cn.hutool.core.date.DateUtil.parse(endTime,"yyyy-MM");
            Date newDate = cn.hutool.core.date.DateUtil.offset(date, DateField.MONTH, 1);
            String formatDate = cn.hutool.core.date.DateUtil.formatDate(newDate);
//            wrapper.ge("demand_time",startTime).le("demand_time","2021-06");
            wrapper.between("demand_time",startTime,formatDate);
        }
        if (StrUtil.isNotEmpty(projectName)){
            wrapper.eq("projectName",projectName);
        }
        //倒叙
        wrapper.eq("del_status",statusCode.Default.getValue()).select("distinct projectName");
        demandPage = demandService.page(demandPage, wrapper);

        List<Demand> demandList = demandPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        List<Map<String,Object>> returnList = new ArrayList<>();
        for (Demand demand:demandList){
            Map<String,Object> project = projectService.getMap(new QueryWrapper<Project>().
                    eq("project_name",demand.getProjectName()).eq("status", statusCode.Default.getValue()));// 获取单个项目
            if (project != null){
                returnList.add(project);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", demandPage.getTotal());
        map.put("data", returnList);
        return map;
    }

    @GetMapping("/two")
    public ModelAndView indexTwo(@RequestParam(required = false) String projectName) {
        ModelAndView modelAndView = new ModelAndView();
        List<Label> labelList = labelService.list(new QueryWrapper<Label>().eq("status",statusCode.Default.getValue())
                .select("label_name"));
        modelAndView.addObject("labelList", labelList);
        modelAndView.addObject("projectName", projectName);
        modelAndView.setViewName("system/index/indexTwo");
        return modelAndView;
    }

    // 列表数据2
    @RequestMapping(value = "/getTwoList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTwoList(
            @RequestParam(value = "page") int page,
            @RequestParam(value = "limit") int limit,
            @RequestParam(value = "projectName",required = true) String projectName,
            @RequestParam(value = "startTime",required = false) String startTime,
            @RequestParam(value = "endTime",required = false) String endTime,
            @RequestParam(value = "labelOption",required = false) String labelOption) {
        IPage<Demand> demandPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<Demand> wrapper = new QueryWrapper<>();
        //判断一下是否有搜索条件
        if (StrUtil.isNotEmpty(labelOption)){
            wrapper.like("label_name",labelOption);
        }
        if (StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime)){
//            wrapper.ge("demand_time", startTime).le("demand_time", endTime);
            wrapper.ge("sum_month", startTime).le("sum_month", endTime);
        }
        wrapper.eq("projectName",projectName);
        wrapper.select("distinct sum_month");
        demandPage = demandService.page(demandPage, wrapper);

        List<Demand> demandList = demandPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        List<Map<String,String>> returnList = new ArrayList<>();
        // 下面循环是为了获取不重复月份数据后拼接数据
        for (Demand demand : demandList){
            Map<String,String> insertList = new HashMap<>();
            String Month = demand.getSumMonth();
            Map<String,Object> filterMap = new HashMap<>();
            filterMap.put("sum_month",Month);
            filterMap.put("projectName",projectName);
            List<Demand> list = demandService.listByMap(filterMap);// 获取单个月份下的所有数据
            if (list.size() > 1){ //如果月份下为多个数据
                String jsonLabel = "";
                String jsonMonth = "";
                for (Demand demand1:list){
                    // 循环标签，如果标签存在则不添加
                    for (String label : demand1.getLabelName().split(",")) {
                        if (!jsonLabel.contains(label)){
                            jsonLabel = jsonLabel.concat(label.concat(","));
                        }
                    }
                    //判断月份是否存在，防止重复添加数据
                    if (!jsonMonth.contains(demand1.getSumMonth())){
                        jsonMonth = jsonMonth.concat(demand1.getSumMonth());
                    }
                }
//                insertList.put("id", String.valueOf(list.get(0).getId()));
                insertList.put("sumMonth", jsonMonth);
                insertList.put("labelName", jsonLabel);
                insertList.put("projectName", projectName);
                returnList.add(insertList);
            }else {// 月份下单个数据
//                insertList.put("id", String.valueOf(list.get(0).getId()));
                insertList.put("sumMonth",Month);
                insertList.put("labelName",list.get(0).getLabelName());
                insertList.put("projectName",projectName);
                returnList.add(insertList);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", demandPage.getTotal());
        map.put("data", returnList);
        return map;
    }

    @GetMapping("/three")
    public ModelAndView indexThree(@RequestParam(required = true) String projectName,
                                   @RequestParam(required = true) String sumMonth) {
        ModelAndView modelAndView = new ModelAndView();
        List<Label> labelList = labelService.list(new QueryWrapper<Label>().eq("status",statusCode.Default.getValue())
                .select("label_name"));
        modelAndView.addObject("labelList", labelList);
        modelAndView.addObject("projectName", projectName);
        modelAndView.addObject("sumMonth", sumMonth);
        modelAndView.setViewName("system/index/indexThree");
        return modelAndView;
    }

    // 列表数据3
    @RequestMapping(value = "/getThreeList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getThreeList(
            @RequestParam(value = "page") int page,
            @RequestParam(value = "limit") int limit,
            @RequestParam(value = "projectName",required = true) String projectName,
            @RequestParam(value = "sumMonth",required = true) String sumMonth,
            @RequestParam(value = "startTime",required = false) String startTime,
            @RequestParam(value = "endTime",required = false) String endTime,
            @RequestParam(value = "labelOption",required = false) String labelOption) {
        String[] monthList = sumMonth.split("-");
        String StartTime = DateUtil.getFirstDayOfMonth(Convert.toInt(monthList[0]),Convert.toInt(monthList[1]));
        String EndTime = DateUtil.getLastDayOfMonth(Convert.toInt(monthList[0]),Convert.toInt(monthList[1]));
        IPage<Demand> demandPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<Demand> wrapper = new QueryWrapper<>();
        //判断一下是否有搜索条件
        boolean filter_status = false;
        // 这里存在优先级问题，如果有搜索时间条件按搜索条件为准，没有则按照默认跳转进来页面时间为准
        if (StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime)){
            wrapper.ge("demand_time", startTime).le("demand_time", endTime);
            filter_status = true;
        }
        if (StrUtil.isNotEmpty(labelOption)){
            wrapper.like("label_name",labelOption);
            filter_status = true;
        }
        if (filter_status){
            wrapper.orderByDesc("demand_time");
            wrapper.eq("projectName",projectName);
            demandPage = demandService.page(demandPage, wrapper);
        } else{
            demandPage = demandService.page(demandPage, new QueryWrapper<Demand>().eq("projectName",projectName)
                    .ge("demand_time", StartTime).le("demand_time", EndTime).orderByDesc("demand_time"));
        }
        List<Demand> demandList = demandPage.getRecords(); //获取数据，这里面还有当前页码数还有总数据参数
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", demandPage.getTotal());
        map.put("data", demandList);
        map.put("sumMonth",sumMonth);
        return map;
    }
}
